#    Copyright 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import COOPGIS_ReportLabStakerReport, COOPGIS_FormGeography, COOPGIS_Misc, COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def BuildRoadEditorForm(DefaultMap):
    from django.contrib import admin
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all()
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['WKTLine']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['id']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['ImportTraceToRoadIndicator']=forms.BooleanField(required=False)
    Dict['ClearSelectionIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)
    Dict['SnapDistance']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'4'}))  
    Dict['DeleteIndicator']=forms.BooleanField(required=False)
    Dict['SelectStationTagNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'4'}))
    Dict['SelectStationid']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'3'}))
    Dict['SelectGPSIndicator']=forms.BooleanField(required=False)
    Dict['SelectionPointSearchDistance']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['SelectionNameLimiter']=forms.CharField(max_length=25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
    Dict['SelectOnlyOneSegmentIndicator']=forms.BooleanField(required=False)
    Dict['NewName']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['ChangeNameIndicator']=forms.BooleanField(required=False)
    Dict['NewUSHighwayIndicator']=forms.BooleanField(required=False)
    Dict['ChangeUSHighwayIndicator']=forms.BooleanField(required=False)
    Dict['NewStateHighwayIndicator']=forms.BooleanField(required=False)
    Dict['ChangeStateHighwayIndicator']=forms.BooleanField(required=False)
    Dict['NewInterstateIndicator']=forms.BooleanField(required=False)
    Dict['ChangeInterstateIndicator']=forms.BooleanField(required=False)
    Dict['NewMainRoadIndicator']=forms.BooleanField(required=False)
    Dict['ChangeMainRoadIndicator']=forms.BooleanField(required=False)
    Dict['NewLeftFromAddress']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['ChangeLeftFromAddressIndicator']=forms.BooleanField(required=False)
    Dict['NewLeftToAddress']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['ChangeLeftToAddressIndicator']=forms.BooleanField(required=False)
    Dict['NewRightFromAddress']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['ChangeRightFromAddressIndicator']=forms.BooleanField(required=False)
    Dict['NewRightToAddress']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['ChangeRightToAddressIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessRoadEditorFormSetSelection(form, UserName):
    ClearSelectionIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ClearSelectionIndicator')
    SelectionPointSearchDistance=COOPGIS_FormMisc.FormGetFloat(form, 'SelectionPointSearchDistance', 5)
    SelectionNameLimiter=COOPGIS_FormMisc.FormGetString(form, 'SelectionNameLimiter')
    SelectOnlyOneSegmentIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'SelectOnlyOneSegmentIndicator')
    #Clear the selection everytime the form is processed
    Road().ClearSelection(UserName)
    SelectionPoint.objects.filter(UserName=UserName).delete()
    if(ClearSelectionIndicator):
        return None, [], ''
    selectionPoint, GPSStatus = COOPGIS_FormGeography.SetSelectionPoint(form, UserName)
    if(not selectionPoint):
        return None, [], GPSStatus
    #raise(Exception(str(selectionPoint.Point)))
    SearchPoint=selectionPoint.Point.transform(djangoproject.settings.COOPGISSRID, clone=True)
    Roads=Road.objects.filter(Line__dwithin=(SearchPoint, SelectionPointSearchDistance))  
    if(SelectOnlyOneSegmentIndicator and Roads):
        Roads=[Roads[0]]
    if(Roads):
        for road in Roads:
            road.SelectionUserName = UserName
            road.save()
    return selectionPoint, Roads, GPSStatus




def ProcessRoadEditorFormMakeChanges(form, selectionPoint, Roads, UserName):
    import models
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    ImportTraceToRoadIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ImportTraceToRoadIndicator')
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    DeleteIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteIndicator')
    SnapDistance=COOPGIS_FormMisc.FormGetFloat(form, 'SnapDistance', 10.0)
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    id=COOPGIS_FormMisc.FormGetInteger(form, 'id', None)
    line=COOPGIS_FormMisc.FormGetGeometryFromWKT(form, 'WKTLine')
    NewName=COOPGIS_FormMisc.FormGetString(form, 'NewName')
    ChangeNameIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ChangeNameIndicator')
    NewUSHighwayIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewUSHighwayIndicator')
    ChangeUSHighwayIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ChangeUSHighwayIndicator')
    NewStateHighwayIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewStateHighwayIndicator')
    ChangeStateHighwayIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ChangeStateHighwayIndicator')
    NewInterstateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewInterstateIndicator')
    ChangeInterstateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ChangeInterstateIndicator')
    NewMainRoadIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewMainRoadIndicator')
    ChangeMainRoadIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ChangeMainRoadIndicator')
    NewLeftFromAddress=COOPGIS_FormMisc.FormGetInteger(form, 'NewLeftFromAddress', 0)
    ChangeLeftFromAddressIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ChangeLeftFromAddressIndicator')
    NewLeftToAddress=COOPGIS_FormMisc.FormGetInteger(form, 'NewLeftToAddress', 0)
    ChangeLeftToAddressIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ChangeLeftToAddressIndicator')
    NewRightFromAddress=COOPGIS_FormMisc.FormGetInteger(form, 'NewRightFromAddress', 0)
    ChangeRightFromAddressIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ChangeRightFromAddressIndicator')
    NewRightToAddress=COOPGIS_FormMisc.FormGetInteger(form, 'NewRightToAddress', 0)
    ChangeRightToAddressIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ChangeRightToAddressIndicator')
    tempcommand=command.Command()
    if(NewIndicator):
        if(ImportTraceToRoadIndicator):
            line=GPSTrace().GetLine()
            line=geography.SnapLineToRoad(line, SnapDistance, djangoproject.settings.COOPGISSRID)
        else:
            line=geography.SnapLineToRoad(line, SnapDistance)
        tempcommand=tempcommand.Create(Name='CreateRoad', ObjectName=NewName, Line=line, InterstateIndicator=NewInterstateIndicator,
                                       USHighwayIndicator=NewUSHighwayIndicator, StateHighwayIndicator=NewStateHighwayIndicator,
                                       MainRoadIndicator=NewMainRoadIndicator, LeftFromAddress=NewLeftFromAddress, 
                                       LeftToAddress=NewLeftToAddress, RightFromAddress=NewRightFromAddress, RightToAddress=NewRightToAddress, 
                                       CommandUserName=UserName)
        road=tempcommand.Process()
        return road
    elif(UpdateIndicator):
        for road in Roads:
            UpdateRoad(road, UserName, NewName, ChangeNameIndicator, NewUSHighwayIndicator, ChangeUSHighwayIndicator, NewStateHighwayIndicator,
                       ChangeStateHighwayIndicator, NewInterstateIndicator, ChangeInterstateIndicator, NewMainRoadIndicator,
                       ChangeMainRoadIndicator, NewLeftFromAddress, ChangeLeftFromAddressIndicator, NewLeftToAddress, 
                       ChangeLeftToAddressIndicator, ChangeRightFromAddressIndicator, NewRightFromAddress,
                       ChangeRightToAddressIndicator, NewRightToAddress)
    elif(DeleteIndicator):
        for road in Roads:
            if(road.ResidesOnServerIndicator):
                tempcommand=tempcommand.Create(Name='DeleteRoad', Objectid=road.id, CommandUserName=UserName)
                tempcommand.Process()
            else:
                road.CreateCommand.delete()
                road.delete()
    return #End of Form Processing
                    



        
def UpdateRoad(road, UserName, NewName, ChangeNameIndicator, NewUSHighwayIndicator, ChangeUSHighwayIndicator, NewStateHighwayIndicator,
               ChangeStateHighwayIndicator, NewInterstateIndicator, ChangeInterstateIndicator, NewMainRoadIndicator,
               ChangeMainRoadIndicator, NewLeftFromAddress, ChangeLeftFromAddressIndicator, NewLeftToAddress, 
               ChangeLeftToAddressIndicator, ChangeRightFromAddressIndicator, NewRightFromAddress,
               ChangeRightToAddressIndicator, NewRightToAddress):
    if(ChangeNameIndicator):
        UpdateName=NewName
    else:
        UpdateName=road.Name
    if(ChangeUSHighwayIndicator):
        UpdateUSHighwayIndicator=NewUSHighwayIndicator
    else:
        UpdateUSHighwayIndicator=road.USHighwayIndicator
    if(ChangeStateHighwayIndicator):
        UpdateStateHighwayIndicator=NewStateHighwayIndicator
    else:
        UpdateStateHighwayIndicator=road.StateHighwayIndicator
    if(ChangeInterstateIndicator):
        UpdateInterstateIndicator=NewInterstateIndicator
    else:
        UpdateInterstateIndicator=road.InterstateIndicator
    if(ChangeMainRoadIndicator):
        UpdateMainRoadIndicator=NewMainRoadIndicator
    else:
        UpdateMainRoadIndicator=road.MainRoadIndicator
    if(ChangeLeftFromAddressIndicator):
        UpdateLeftFromAddress=NewLeftFromAddress
    else:
        UpdateLeftFromAddress=road.LeftFromAddress
    if(ChangeRightFromAddressIndicator):
        UpdateRightFromAddress=NewRightFromAddress
    else:
        UpdateRightFromAddress=road.RightFromAddress
    if(ChangeLeftToAddressIndicator):
        UpdateLeftToAddress=NewLeftToAddress
    else:
        UpdateLeftToAddress=road.LeftToAddress
    if(ChangeRightToAddressIndicator):
        UpdateRightToAddress=NewRightToAddress
    else:
        UpdateRightToAddress=road.RightToAddress
    Roadid, IndexWhenReverseSorted=road.GetCommandidData()
    tempcommand=Command().Create(Name='EditRoad', CommandUserName=UserName, ObjectName=NewName, Line=road.Line, 
                                   InterstateIndicator=NewInterstateIndicator,
                                   USHighwayIndicator=NewUSHighwayIndicator, StateHighwayIndicator=NewStateHighwayIndicator,
                                   MainRoadIndicator=NewMainRoadIndicator, LeftFromAddress=NewLeftFromAddress, 
                                   LeftToAddress=NewLeftToAddress, RightFromAddress=NewRightFromAddress, 
                                   RightToAddress=NewRightToAddress, 
                                   Objectid=Roadid, IndexWhenReverseSorted=IndexWhenReverseSorted)
    road=tempcommand.Process()




def PopulateRoadEditorForm(form, selectionPoint):
    form.setData({'ClearSelectionIndicator': False})
    form.setData({'NewIndicator': False})
    form.setData({'UpdateIndicator': False})
    form.setData({'DeleteIndicator': False})
    #form.setData({'SelectStationTagNumber': ''})
    #form.setData({'SelectStationid': ''})
    form.setData({'SelectGPSIndicator': False})
    form.setData({'ChangeNameIndicator': False})
    form.setData({'ChangeUSHighwayIndicator': False})
    form.setData({'ChangeStateHighwayIndicator': False})
    form.setData({'ChangeInterstateIndicator': False})
    form.setData({'ChangeMainRoadIndicator': False})
    form.setData({'ChangeLeftFromAddressIndicator': False})
    form.setData({'ChangeLeftToAddressIndicator': False})
    form.setData({'ChangeRightFromAddressIndicator': False})
    form.setData({'ChangeRightToAddressIndicator': False})
    form.setData({'ImportTraceToRoadIndicator':False})
    form.data['WKTLine']=''
    return form

